package Tree;

import java.util.LinkedList;
import java.util.Queue;

public class _814_BinaryTreePruning {
    Queue<TreeNode> queue = new LinkedList<>();
    public TreeNode pruneTree_1(TreeNode root) {
        if (root == null) {
            return null;
        }
        queue.add(root);
        addNode(root);
        while (!queue.isEmpty()) {
            TreeNode temp = queue.poll();
            if (allZero(temp.left)) {
                temp.left = null;
            }
            if (allZero(temp.right)) {
                temp.right = null;
            }
        }
        if (root.left == null && root.right == null && root.val == 0) {
            return null;
        }
        return root;
    }

    public void addNode(TreeNode temp) {
        if (temp != null) {
            if (temp.left != null) {
                queue.add(temp.left);
                addNode(temp.left);
            }
            if (temp.right != null) {
                queue.add(temp.right);
                addNode(temp.right);
            }
        }
    }
    public boolean allZero(TreeNode temp) {
        if (temp == null) {
            return true;
        } else {
            if (temp.val == 1) {
                return false;
            } else {
                return (allZero(temp.left) && allZero(temp.right));
            }
        }
    }

    //reference solution: use recursion and delete duplicated calculation.
    public TreeNode pruneTree(TreeNode root) {
        if (prune(root)) {
            return null;
        }
        return root;
    }

    public boolean prune(TreeNode temp) {
        if (temp == null) {
            return true;
        }
        boolean left = prune(temp.left);
        boolean right = prune(temp.right);
        if (left && right && temp.val == 0) {
            return true;
        }
        if (left) {
            temp.left = null;
        }
        if (right) {
            temp.right = null;
        }
        return false;
    }
}
